package tmt.usercenter.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import tmt.usercenter.web.service.ClientSystemService;
import tmt.usercenter.web.vo.ClientVo;

import javax.validation.Valid;

@Controller
@RequestMapping("/client")
public class ClientController {

	@Autowired
	private ClientSystemService clientService;

	@RequestMapping({"", "/", "/index"})
	public String clientList() {
		return "client/user-client-list";
	}

	@RequestMapping("/apply")
	public String clientApply(Model model) {
		model.addAttribute("model", new ClientVo());
		return "client/user-client-apply";
	}

	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	public String clientApply(@Valid @ModelAttribute("model") ClientVo clientVo, BindingResult result) {
		boolean clientNameExist = clientService.existsByClientName(clientVo.getName());
		if (clientNameExist) {
			result.rejectValue("name", null, "应用名称已存在。");
		}
		boolean clientIdExist = clientService.existsByClientId(clientVo.getClientId());
		if (clientIdExist) {
			result.rejectValue("clientId", null, "应用编号已存在。");
		}

		if (result.hasErrors()) {
			return "client/user-client-apply";
		}

		return null;
	}

	@RequestMapping("/{clientId}")
	public String client(@PathVariable String clientId) {
		return "client/user-client-detail";
	}

	@RequestMapping("/{clientId}/users")
	public String clientUsers(@PathVariable String clientId) {
		return "client/user-client-users";
	}

}